#include "weather.h"
#include <QDebug>
#include <QEvent>
#include <QTime>
#include <QFont>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDateTime>
#include <QImage>
#include <QTableWidgetItem>
#include <QHeaderView>
#include <QTimer>
#include <QRegularExpression>

#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>

#include <QDomDocument>
#include <QTextCodec>
#include <DToolBar>



weather::weather(DWidget *parent) : DMainWindow(parent)
{

    //初始化天气图片对应map
    initWeatherMap();
    this->setMinimumSize(1200,675);
    mNetAccessManager = new QNetworkAccessManager(this);
    getWearherImage = new QNetworkAccessManager(this);
    getWearherTop = new QNetworkAccessManager(this);
    connect(mNetAccessManager,&QNetworkAccessManager::finished,this,&weather::onReplied);
    connect(getWearherTop,&QNetworkAccessManager::finished,this,&weather::onRepliedWeatherTop);
    connect(getWearherImage,&QNetworkAccessManager::finished,this,&weather::onRepliedImage);

    mDialog = new  DDialog();
    dialogWidget =  new DWidget();
    mDialog->addContent(dialogWidget);
    mDialog->setMinimumSize(1000,800);

    //整体布局
    rootWidget = new DWidget(this);
    //整体垂直布局
    rootVlayout = new QVBoxLayout(rootWidget);
    initUpWidget();
    initDownWidget();
    rootVlayout->addWidget(rootUpWidget);
    rootVlayout->addWidget(rootDownWidget);
    setLayout(rootVlayout);
    this->setCentralWidget(rootWidget);
    QTimer *timer = new QTimer();
    connect(timer, &QTimer::timeout, this,[=]{
        cityCode m;
        QString citycode = m.getCityCode(mToday.city.split(",").last().trimmed());
        getWeather(citycode);
    });
    timer->start(6000);
    getWeather("54514");
    openBrowser = new browser();

}

void weather::onReplied(QNetworkReply *reply)
{
    int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    if (reply->error() != QNetworkReply::NoError||status !=200){
        qDebug()<<"error";
    }else{
        QByteArray bytrarry  =  reply->readAll();
        updateWeatherDate(bytrarry);
    }
    //释放堆内存
    reply->deleteLater();
}

void weather::onRepliedImage(QNetworkReply *reply)
{
    int status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    QUrl url = reply->request().url();

    if (reply->error() != QNetworkReply::NoError||status !=200){
        qDebug()<<"error";
    }else{
        QByteArray byteArray  =  reply->readAll();
        QImage image;
        image.loadFromData(byteArray);
        QString  * fileName = nullptr;
        if (url.toString().contains("SEVP_NMC_STFC_SFER_ER24_ACHN_L88_P9")){
            fileName = new QString("/tmp/1.png");
        }else if(url.toString().contains("SEVP_NSMC_WXBL_FY4B_ETCC_ACHN_LNO_PY")){
            fileName = new QString("/tmp/2.png");
        }else if(url.toString().contains("SEVP_NMC_CDWP_SFER_EME_ACHN_LNO_P9")){
            fileName = new QString("/tmp/3.png");
        }else if (url.toString().contains("SEVP_NMC_TRFC_SFER_EME_ACHN_L88_P9")){
            fileName = new QString("/tmp/4.png");
        }
        image.save(*fileName, "PNG");
    }
    //释放堆内存
    reply->deleteLater();
}

void weather::onRepliedWeatherTop(QNetworkReply *reply)
{
    if (reply->error() == QNetworkReply::NoError) {
            QByteArray data = reply->readAll();
            // 解析XML数据
            xmlDocPtr doc = xmlReadMemory(data.data(), data.size(), "", NULL, XML_PARSE_RECOVER | XML_PARSE_NOERROR | XML_PARSE_NOWARNING);
            if (!doc) {
                qDebug() << "Failed to parse the XML document.";
                return;
            }
            xmlNodePtr node = xmlDocGetRootElement(doc);
            if (!node) {
                qDebug() << "No root element found.";
                xmlFreeDoc(doc);
                return;
            }

            xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc);
            if (!xpathCtx) {
                qWarning() << "Failed to create XPath context.";
                xmlFreeDoc(doc);
                return;
            }
            const xmlChar* xpathExpr = (xmlChar *)"//*[@id='HOT']/a";
            xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression(xpathExpr, xpathCtx);
            if (!xpathObj) {
                qWarning() << "XPath evaluation failed.";
                xmlXPathFreeContext(xpathCtx);
                xmlFreeDoc(doc);
                return;
            }
            if (!xpathObj->nodesetval) {
                qWarning() << "XPath evaluation returned no nodeset.";
                xmlXPathFreeObject(xpathObj);
                xmlXPathFreeContext(xpathCtx);
                xmlFreeDoc(doc);
                return;
            }
            int nodeCount = xpathObj->nodesetval->nodeNr;
            for (int i = 0; i < nodeCount; ++i) {
                QStringList sublist;
                xmlNodePtr aTag = xpathObj->nodesetval->nodeTab[i];
                // 遍历每个a标签的子节点
                xmlNodePtr child = aTag->children;
                while (child) {
                    if (child->type == XML_ELEMENT_NODE && xmlStrEqual(child->name, (const xmlChar *)"div")) {
                        // 处理div节点的内容
                        xmlNodePtr divChild = child->children;
                        while (divChild) {
                            if (divChild->type == XML_TEXT_NODE) {
                                QString divContent = QString::fromUtf8(reinterpret_cast<const char*>(divChild->content));
                                if (divContent.contains(QRegularExpression("排名|城市|省份|最高温度"))){
                                    break;
                                }else{
                                    sublist.append(divContent.trimmed());
                                }
                            }
                            divChild = divChild->next;
                        }
                    }
                    child = child->next;
                }
                if (!sublist.isEmpty()){
                    listTop.append(sublist);
                }
            }
        updataDownRighttableHighTemperature(listTop);

        //今日低温----------------------------
        const xmlChar* xpathExprHB = (xmlChar *)"//*[@id='HB']/a";
        xmlXPathObjectPtr xpathObjHB = xmlXPathEvalExpression(xpathExprHB, xpathCtx);
        if (!xpathObjHB) {
            qWarning() << "XPath evaluation failed.";
            xmlXPathFreeContext(xpathCtx);
            xmlFreeDoc(doc);
            return;
        }
        if (!xpathObjHB->nodesetval) {
            qWarning() << "XPath evaluation returned no nodeset.";
            xmlXPathFreeObject(xpathObjHB);
            xmlXPathFreeContext(xpathCtx);
            xmlFreeDoc(doc);
            return;
        }
        int nodeCountHB = xpathObjHB->nodesetval->nodeNr;
        for (int i = 0; i < nodeCountHB; ++i) {
            QStringList sublist;
            xmlNodePtr aTag = xpathObjHB->nodesetval->nodeTab[i];
            // 遍历每个a标签的子节点
            xmlNodePtr child = aTag->children;
            while (child) {
                if (child->type == XML_ELEMENT_NODE && xmlStrEqual(child->name, (const xmlChar *)"div")) {
                    // 处理div节点的内容
                    xmlNodePtr divChild = child->children;
                    while (divChild) {
                        if (divChild->type == XML_TEXT_NODE) {
                            QString divContent = QString::fromUtf8(reinterpret_cast<const char*>(divChild->content));
                            if (divContent.contains(QRegularExpression("排名|城市|省份|最低温度"))){
                                break;
                            }else{
                                sublist.append(divContent.trimmed());
                            }
                        }
                        divChild = divChild->next;
                    }
                }
                child = child->next;
            }
            if (!sublist.isEmpty()){
                listTopHB.append(sublist);
            }
        }

        updataDownRighttableLowTemperature(listTopHB);


        //今日温差----------------------------
        const xmlChar* xpathExprDB = (xmlChar *)"//*[@id='DB']/a";
        xmlXPathObjectPtr xpathObjDB = xmlXPathEvalExpression(xpathExprDB, xpathCtx);
        if (!xpathObjDB) {
            qWarning() << "XPath evaluation failed.";
            xmlXPathFreeContext(xpathCtx);
            xmlFreeDoc(doc);
            return;
        }
        if (!xpathObjDB->nodesetval) {
            qWarning() << "XPath evaluation returned no nodeset.";
            xmlXPathFreeObject(xpathObjDB);
            xmlXPathFreeContext(xpathCtx);
            xmlFreeDoc(doc);
            return;
        }
        int nodeCountDB = xpathObjHB->nodesetval->nodeNr;
        for (int i = 0; i < nodeCountDB; ++i) {
            QStringList sublist;
            xmlNodePtr aTag = xpathObjDB->nodesetval->nodeTab[i];
            // 遍历每个a标签的子节点
            xmlNodePtr child = aTag->children;
            while (child) {
                if (child->type == XML_ELEMENT_NODE && xmlStrEqual(child->name, (const xmlChar *)"div")) {
                    // 处理div节点的内容
                    xmlNodePtr divChild = child->children;
                    while (divChild) {
                        if (divChild->type == XML_TEXT_NODE) {
                            QString divContent = QString::fromUtf8(reinterpret_cast<const char*>(divChild->content));
                            if (divContent.contains(QRegularExpression("排名|城市|省份|温差"))){
                                break;
                            }else{
                                sublist.append(divContent.trimmed());
                            }
                        }
                        divChild = divChild->next;
                    }
                }
                child = child->next;
            }
            if (!sublist.isEmpty()){
                listTopDB.append(sublist);
            }
        }
        updataDownRighttableDBTemperature(listTopDB);


        //24小时降水----------------------------
        const xmlChar* xpathExprHD = (xmlChar *)"//*[@id='HD']/a";
        xmlXPathObjectPtr xpathObjHD = xmlXPathEvalExpression(xpathExprHD, xpathCtx);
        if (!xpathObjHD) {
            qWarning() << "XPath evaluation failed.";
            xmlXPathFreeContext(xpathCtx);
            xmlFreeDoc(doc);
            return;
        }
        if (!xpathObjHD->nodesetval) {
            qWarning() << "XPath evaluation returned no nodeset.";
            xmlXPathFreeObject(xpathObjHD);
            xmlXPathFreeContext(xpathCtx);
            xmlFreeDoc(doc);
            return;
        }
        int nodeCountHD = xpathObjHD->nodesetval->nodeNr;
        for (int i = 0; i < nodeCountHD; ++i) {
            QStringList sublist;
            xmlNodePtr aTag = xpathObjHD->nodesetval->nodeTab[i];
            // 遍历每个a标签的子节点
            xmlNodePtr child = aTag->children;
            while (child) {
                if (child->type == XML_ELEMENT_NODE && xmlStrEqual(child->name, (const xmlChar *)"div")) {
                    // 处理div节点的内容
                    xmlNodePtr divChild = child->children;
                    while (divChild) {
                        if (divChild->type == XML_TEXT_NODE) {
                            QString divContent = QString::fromUtf8(reinterpret_cast<const char*>(divChild->content));
                            if (divContent.contains(QRegularExpression("排名|城市|省份|降水量"))){
                                break;
                            }else{
                                sublist.append(divContent.trimmed());
                            }
                        }
                        divChild = divChild->next;
                    }
                }
                child = child->next;
            }
            if (!sublist.isEmpty()){
                listTopHD.append(sublist);
            }
        }
        updataDownRighttableHDTemperature(listTopHD);

        //获取url

        const xmlChar* xpathExprHUrl = (xmlChar *)"//*[@class='hd']/ul/li//div/img";
        xmlXPathObjectPtr xpathObjUrl = xmlXPathEvalExpression(xpathExprHUrl, xpathCtx);
        if (!xpathObjUrl) {
            qWarning() << "XPath evaluation failed.";
            xmlXPathFreeContext(xpathCtx);
            xmlFreeDoc(doc);
            return;
        }
        if (!xpathObjUrl->nodesetval) {
            qWarning() << "XPath evaluation returned no nodeset.";
            xmlXPathFreeObject(xpathObjUrl);
            xmlXPathFreeContext(xpathCtx);
            xmlFreeDoc(doc);
            return;
        }
        // 遍历XPath结果
           xmlNodeSetPtr nodes = xpathObjUrl->nodesetval;
           int index =1;
           if (nodes != NULL) {
               for (int i = 0; i < nodes->nodeNr; i++) {
                   xmlNodePtr cur = nodes->nodeTab[i];
                   // 获取src属性
                   xmlChar* src = xmlGetProp(cur, BAD_CAST "src");
                   if (src != NULL) {

                       QString url = reinterpret_cast<const char*>(src);
                       if (url.contains("https://")){
                           if (index <5){
                            getWearherImage->get(QNetworkRequest(url));
                            index+=1;
                           }
                       }
                       xmlFree(src);
                   }
               }
           }

        //今日资讯

           const xmlChar* xpathExprHNews = (xmlChar *)"//*[@class='hb']/a";
           xmlXPathObjectPtr xpathObjNews = xmlXPathEvalExpression(xpathExprHNews, xpathCtx);
           if (!xpathObjNews) {
               qWarning() << "XPath evaluation failed.";
               xmlXPathFreeContext(xpathCtx);
               xmlFreeDoc(doc);
               return;
           }
           if (!xpathObjNews->nodesetval) {
               qWarning() << "XPath evaluation returned no nodeset.";
               xmlXPathFreeObject(xpathObjNews);
               xmlXPathFreeContext(xpathCtx);
               xmlFreeDoc(doc);
               return;
           }
           // 遍历XPath结果
              xmlNodeSetPtr nodesNews = xpathObjNews->nodesetval;
              if (nodes != NULL) {
                  QMap<QString,QString> weatherNews;
                  for (int i = 0; i < nodesNews->nodeNr; i++) {
                      xmlNodePtr cur = nodesNews->nodeTab[i];
                      // 获取src属性
                      xmlChar* href = xmlGetProp(cur, BAD_CAST "href");
                      xmlChar* title = xmlGetProp(cur, BAD_CAST "title");
                      if (href != NULL && title != NULL ) {

                          QString url = reinterpret_cast<const char*>(href);
                          QString mtitle = reinterpret_cast<const char*>(title);
                          if (url.contains("www.cma.gov.cn")){
                              weatherNews.insert(mtitle,url);
                          }
                      }
                      xmlFree(href);
                  }
                    updateDownRighttableNews(weatherNews);
                  }

        reply->deleteLater();
    }
}

void weather::initWeatherMap()
{
    weatherMap.insert("暴雪",":/images/weatherIcon/BaoXue.png");
    weatherMap.insert("雨夹雪",":/images/weatherIcon/YuJiaXue.png");
    weatherMap.insert("暴雨",":/images/weatherIcon/BaoYu.png");
    weatherMap.insert("暴雨到大暴雨",":/images/weatherIcon/BaoYuDaoDaBaoYu.png");
    weatherMap.insert("大到暴雨",":/images/weatherIcon/DaDaoBaoYu.png");
    weatherMap.insert("大到暴雪",":/images/weatherIcon/DaDaoBaoXue.png");
    weatherMap.insert("大雪",":/images/weatherIcon/DaXue.png");
    weatherMap.insert("大雨",":/images/weatherIcon/DaYu.png");
    weatherMap.insert("大暴雨",":/images/weatherIcon/DaBaoYu.png");
    weatherMap.insert("冻雨","：/images/weatherIcon/DongYu.png");
    weatherMap.insert("多云",":/images/weatherIcon/DuoYun.png");
    weatherMap.insert("浮尘",":/images/weatherIcon/FuChen.png");
    weatherMap.insert("雷阵雨伴有冰雹",":/images/weatherIcon/LeiZhenYuBanYouBingBao.png");
    weatherMap.insert("霾",":/images/weatherIcon/Mai.png");
    weatherMap.insert("晴",":/images/weatherIcon/Qing.png");
    weatherMap.insert("小雨",":/images/weatherIcon/XiaoYu.png");
    weatherMap.insert("雷阵雨",":/images/weatherIcon/LeiZhenYu.png");
    weatherMap.insert("沙尘暴",":/images/weatherIcon/ShaChenBao.png");
    weatherMap.insert("小雨",":/images/weatherIcon/XiaoYu.png");
    weatherMap.insert("阵雨",":/images/weatherIcon/ZhenYu.png");
    weatherMap.insert("pm25",":/images/weatherIcon/pm25.png");
    weatherMap.insert("pm25",":/images/weatherIcon/pm25.png");
    weatherMap.insert("阴",":/images/weatherIcon/Yin.png");
    weatherMap.insert("风",":/images/weatherIcon/wind.png");
    weatherMap.insert("中雨",":/images/weatherIcon/ZhongYu.png");
    weatherMap.insert("雾",":/images/weatherIcon/Wu.png");
    weatherMap.insert("小雪",":/images/weatherIcon/XiaoXue.png");
    weatherMap.insert("阵雪",":/images/weatherIcon/ZhenXue.png");
}

void weather::getWeather(QString stationid)
{

    QUrl url("https://weather.cma.cn/api/weather/view?stationid="+stationid);
    QUrl url5("https://weather.cma.cn/");
    mNetAccessManager->get(QNetworkRequest(url));
    getWearherTop->get(QNetworkRequest(url5));
}

bool weather::updateWeatherDate(QByteArray &byteArray)
{
    QJsonParseError err;
    QJsonDocument doc = QJsonDocument::fromJson(byteArray,&err);
    if (err.error != QJsonParseError::NoError){
        return false;
    }else{
        QJsonObject rootObject = doc.object();
        QJsonObject locate =  rootObject.value("data").toObject();
        //写入当前天气数据
        mToday.city = locate.value("location").toObject().value("path").toString();
        mToday.humidity = locate.value("now").toObject().value("humidity").toDouble();
        mToday.precipitation = locate.value("now").toObject().value("precipitation").toDouble();
        mToday.temperature = locate.value("now").toObject().value("temperature").toDouble();
        mToday.pressure = locate.value("now").toObject().value("pressure").toDouble();
        mToday.windDirection = locate.value("now").toObject().value("windDirection").toString();
        mToday.windScale =     locate.value("now").toObject().value("windScale").toString();
        //写入7天数据
//         QJsonArray  weatherArray =  objData.value("forecast").toArray();
         QJsonArray  weatherArray = locate.value("daily").toArray();
         for (int i=0;i<7;i++){
             QJsonObject obgData = weatherArray[i].toObject();
             mDay[i].date = obgData.value("date").toString();
             mDay[i].high = obgData.value("high").toDouble();
             mDay[i].low = obgData.value("low").toDouble();
             mDay[i].dayText = obgData.value("dayText").toString();
             mDay[i].dayWindDirection = obgData.value("dayWindDirection").toString();
             mDay[i].dayWindScale = obgData.value("dayWindScale").toString();
             mDay[i].nightText = obgData.value("nightText").toString();
         }
        updateUiData();
        return true;
    }
}

void weather::updateUiData()
{
    leftLbl1_4->setText(QTime::currentTime().toString("hh:mm"));
    leftLbl2->setText(QString::number(mToday.temperature) + "°C");
    leftLbl5_1->setText(QString::number(mToday.precipitation)+"mm");
    leftLbl5_2->setText(mToday.windScale);
    leftLbl5_3->setText(QString::number(mToday.humidity));
    leftLbl5_4->setText(QString::number(mToday.pressure));
    leftLbl4_2->setText(mToday.windDirection);
    lblZone->setText(mToday.city.split(",")[1] + " | " + mToday.city.split(",")[2] );

    for (int i=0;i<7;i++){
        for (int m=0;m<7;m++){
            if (m==0){
                QString week =  getDayOfWeek(mDay[i].date);
                if (i ==0){
                    week = "今天";
                }else if (i ==1){
                    week = "明天";
                }else if (i ==2){
                    week = "后天";
                }
                lbl[i][m]->setText(week);
            }
            else if (m == 1){
                lbl[i][m]->setAlignment(Qt::AlignHCenter);
                lbl[i][m]->setText(mDay[i].date.split("/")[1] +"/"+ mDay[i].date.split("/")[2]);
            }else if (m == 2){
                lbl[i][m]->setPixmap(QPixmap(weatherMap[mDay[i].dayText]));
            }else if (m == 3){
                lbl[i][m]->setPixmap(QPixmap(weatherMap[mDay[i].nightText]));
            }else if (m == 4){
                lbl[i][m]->setText(QString::number(mDay[i].high) + "/" + QString::number(mDay[i].low));
            }else if (m == 5){
                if (mDay[i].dayText == mDay[i].nightText  ){
                    lbl[i][m]->setText(mDay[i].dayText);
                }else{
                    lbl[i][m]->setText(mDay[i].dayText + "转" + mDay[i].nightText);
                }
            }else if (m == 6){
                lbl[i][m]->setText(mDay[i].dayWindScale);
            }

        }
    }


}

QString weather::getDayOfWeek(const QString &timeStr)
{
    // 时间字符串的格式
    QString format = "yyyy/MM/dd"; // 如果是日期格式
    // 如果是带时间的时间戳
    // QString format = "yyyy-MM-dd hh:mm:ss";

    // 解析时间字符串
    QDateTime dateTime = QDateTime::fromString(timeStr, format);

    // 检查解析是否成功
    if (!dateTime.isValid()) {
        qDebug() << "Invalid date/time string:" << timeStr;
        return "Invalid Date";
    }

    // 获取星期几
    int dayOfWeek = dateTime.date().dayOfWeek();

    // 根据天数转换成中文表示的星期几
    switch(dayOfWeek) {
        case Qt::Monday:
            return "周一";
        case Qt::Tuesday:
            return "周二";
        case Qt::Wednesday:
            return "周三";
        case Qt::Thursday:
            return "周四";
        case Qt::Friday:
            return "周五";
        case Qt::Saturday:
            return "周六";
        case Qt::Sunday:
            return "周日";
        default:
            return "Unknown Day";
    }
}

//void weather::clearLayout(QLayout *layout)
//{
//    QLayoutItem *item;
//    while ((item = layout->takeAt(0)) != nullptr) {
//        if (item->layout()) {
//            clearLayout(item->layout()); // 递归清除子布局
//        }
//        delete item->widget(); // 删除小部件
//        delete item;           // 删除布局项
//    }
//}

//右下角布局
void weather::initDownRightTable()
{
    downRighttable0->setRowCount(8);
    downRighttable0->setColumnCount(2);
    downRighttable0->hideColumn(1);
    downRighttable0->horizontalHeader()->hide();
    downRighttable0->setHorizontalHeaderLabels(horizontallist);
    downRighttable0->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    downRighttable0->setShowGrid(false);//去掉边框网格线
    downRighttable0->verticalHeader()->hide();
    downRighttable0->setEditTriggers(QAbstractItemView::NoEditTriggers);
    downRighttable0->setStyleSheet(
            "QTableView::item {"
            "   color: black;" // 默认字体颜色为黑色
            "}"
            "QTableView::item:hover {"
            "   color: blue;" // 当鼠标悬停时字体变为红色
            "}"
            "QTableView::item:selected {"
            "   background-color: white;" // 选中时背景色为白色
            "   color: black;" // 选中时字体颜色为黑色
            "}"
            "QTableView::item:focus {"
            "   border: none;" // 取消聚焦边框
            "}"
        );

    downRighttable1->setRowCount(10);
    horizontallist<<"排名"<<"城市"<<"省份"<<"最高温度";
    downRighttable1->setColumnCount(4);
    downRighttable1->setHorizontalHeaderLabels(horizontallist);
    downRighttable1->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    downRighttable1->setShowGrid(false);//去掉边框网格线
    downRighttable1->verticalHeader()->hide();
    downRighttable1->setEditTriggers(QAbstractItemView::NoEditTriggers);
    downRighttable1->setStyleSheet("color:black");

    downRighttable2->setRowCount(10);
    QStringList horizontallist1;
    horizontallist1    <<"排名"<<"城市"<<"省份"<<"最低温度";
    downRighttable2->setColumnCount(4);
    downRighttable2->setHorizontalHeaderLabels(horizontallist1);
    downRighttable2->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    downRighttable2->setShowGrid(false);//去掉边框网格线
    downRighttable2->verticalHeader()->hide();
    downRighttable2->setEditTriggers(QAbstractItemView::NoEditTriggers);


    downRighttable3->setRowCount(10);
    QStringList horizontallist2;
    horizontallist2    <<"排名"<<"城市"<<"省份"<<"温差";
    downRighttable3->setColumnCount(4);
    downRighttable3->setHorizontalHeaderLabels(horizontallist2);
    downRighttable3->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    downRighttable3->setShowGrid(false);//去掉边框网格线
    downRighttable3->verticalHeader()->hide();
    downRighttable3->setEditTriggers(QAbstractItemView::NoEditTriggers);


    downRighttable4->setRowCount(10);
    QStringList horizontallist3;
    horizontallist3    <<"排名"<<"城市"<<"省份"<<"24小时降水";
    downRighttable4->setColumnCount(4);
    downRighttable4->setHorizontalHeaderLabels(horizontallist3);
    downRighttable4->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    downRighttable4->setShowGrid(false);//去掉边框网格线
    downRighttable4->verticalHeader()->hide();
    downRighttable4->setEditTriggers(QAbstractItemView::NoEditTriggers);
}

//上层布局
void weather::initUpWidget()
{
    //上层主体布局
    rootUpWidget = new DWidget();
    rootUpWidget->setFixedHeight(270);
    rootUpWidget->setStyleSheet("background-image: url(:/images/bg.png);");

    //上层主体水平布局
    rootUpLayout = new QHBoxLayout(rootUpWidget);
    rootUpLayout->setContentsMargins(0,0,0,0);
    rootUpLayout->setSpacing(0);

    //上层左侧主要布局
    rootUpWidgetLeft = new DWidget();
    rootUpLeftLayout = new QVBoxLayout(rootUpWidgetLeft);
    rootUpLeftLayout->setSpacing(0);
    rootUpLeftHLayout1 = new QHBoxLayout();
    rootUpLeftHLayout1->setSpacing(0);
    rootUpLeftHLayout3 = new QHBoxLayout();
    rootUpLeftHLayout3->setSpacing(0);
    rootUpLeftHLayout4 = new QHBoxLayout();
    rootUpLeftHLayout5 = new QHBoxLayout();


    //第一层
    leftLbl1_1 = new DLabel();
    lblZone = new DLabel("zone");
    lblZone->setStyleSheet("color:white");
    leftLbl1_3 = new DLabel();
    leftLbl1_4 = new DLabel(QTime::currentTime().toString("hh:mm"));
    leftLbl1_4->setStyleSheet("color:white");

    QIcon icon(":/images/clock.svg");
    QPixmap pixmap = icon.pixmap(QSize(25,25));// 设置为50x50像素
    leftLbl1_3->setPixmap(pixmap);
    QIcon iconGps(":/images/GPS.svg");
    QPixmap pixmapGps = iconGps.pixmap(QSize(25,25));// 设置为50x50像素
    leftLbl1_1->setPixmap(pixmapGps);
    rootUpLeftHLayout1->addWidget(leftLbl1_1);
    rootUpLeftHLayout1->addSpacing(5);
    rootUpLeftHLayout1->addWidget(lblZone);
    rootUpLeftHLayout1->addStretch();
    rootUpLeftHLayout1->addWidget(leftLbl1_3);
    rootUpLeftHLayout1->addSpacing(5);
    rootUpLeftHLayout1->addWidget(leftLbl1_4);

    //第二层
    leftLbl2 = new DLabel("16.6°C");
    leftLbl2->setMinimumHeight(100);
    leftLbl2->setStyleSheet("color:white");
    leftLbl2->setAlignment(Qt::AlignCenter);
    leftLbl2->setAttribute(Qt::WA_TranslucentBackground);
    // 创建一个 QFont 对象，并设置字体大小
    QFont font;
    font.setPointSize(30); // 设置字体大小为 16 点

    // 将 QFont 对象应用到 QLabel
    leftLbl2->setFont(font);

    //第三层
    leftLbl3_1 = new DLabel();
    leftLbl3_2 = new DLabel();
    leftLbl3_3 = new DLabel();
    leftLbl3_4 = new DLabel();
    leftLbl3_1->setAttribute(Qt::WA_TranslucentBackground);
    leftLbl3_2->setAttribute(Qt::WA_TranslucentBackground);
    leftLbl3_3->setAttribute(Qt::WA_TranslucentBackground);
    leftLbl3_4->setAttribute(Qt::WA_TranslucentBackground);
    leftLbl3_1->setAlignment(Qt::AlignCenter);
    leftLbl3_2->setAlignment(Qt::AlignCenter);
    leftLbl3_3->setAlignment(Qt::AlignCenter);
    leftLbl3_4->setAlignment(Qt::AlignCenter);
    rootUpLeftHLayout3->addWidget(leftLbl3_1);
    rootUpLeftHLayout3->addWidget(leftLbl3_2);
    rootUpLeftHLayout3->addWidget(leftLbl3_3);
    rootUpLeftHLayout3->addWidget(leftLbl3_4);
    QIcon icon_1(":/images/湿度.svg");
    QPixmap pixmap_1 = icon_1.pixmap(QSize(25,25));// 设置为50x50像素
    leftLbl3_1->setPixmap(pixmap_1);
    QIcon icon_2(":/images/wind.png");
    QPixmap pixmap_2 = icon_2.pixmap(QSize(25,25));// 设置为50x50像素
    leftLbl3_2->setPixmap(pixmap_2);
    QIcon icon_3(":/images/湿度.svg");
    QPixmap pixmap_3 = icon_3.pixmap(QSize(25,25));// 设置为50x50像素
    leftLbl3_3->setPixmap(pixmap_3);
    QIcon icon_4(":/images/气压.svg");
    QPixmap pixmap_4 = icon_4.pixmap(QSize(25,25));// 设置为50x50像素
    leftLbl3_4->setPixmap(pixmap_4);

    //第四层
    leftLbl4_1 = new DLabel("降水");
    leftLbl4_2 = new DLabel("东南风");
    leftLbl4_3 = new DLabel("相对湿度");
    leftLbl4_4 = new DLabel("气压");
    leftLbl4_1->setAttribute(Qt::WA_TranslucentBackground);
    leftLbl4_2->setAttribute(Qt::WA_TranslucentBackground);
    leftLbl4_3->setAttribute(Qt::WA_TranslucentBackground);
    leftLbl4_4->setAttribute(Qt::WA_TranslucentBackground);
    leftLbl4_1->setStyleSheet("color:white");
    leftLbl4_2->setStyleSheet("color:white");
    leftLbl4_3->setStyleSheet("color:white");
    leftLbl4_4->setStyleSheet("color:white");
    leftLbl4_1->setAlignment(Qt::AlignHCenter);
    leftLbl4_2->setAlignment(Qt::AlignHCenter);
    leftLbl4_3->setAlignment(Qt::AlignHCenter);
    leftLbl4_4->setAlignment(Qt::AlignHCenter);
    rootUpLeftHLayout4->addWidget(leftLbl4_1);
    rootUpLeftHLayout4->addWidget(leftLbl4_2);
    rootUpLeftHLayout4->addWidget(leftLbl4_3);
    rootUpLeftHLayout4->addWidget(leftLbl4_4);

    //第五层
    leftLbl5_1 = new DLabel("0mm");
    leftLbl5_2 = new DLabel("微风");
    leftLbl5_3 = new DLabel("63%");
    leftLbl5_4 = new DLabel("1015hpa");
    leftLbl5_1->setAttribute(Qt::WA_TranslucentBackground);
    leftLbl5_2->setAttribute(Qt::WA_TranslucentBackground);
    leftLbl5_3->setAttribute(Qt::WA_TranslucentBackground);
    leftLbl5_4->setAttribute(Qt::WA_TranslucentBackground);
    leftLbl5_1->setStyleSheet("color:white");
    leftLbl5_2->setStyleSheet("color:white");
    leftLbl5_3->setStyleSheet("color:white");
    leftLbl5_4->setStyleSheet("color:white");
    leftLbl5_1->setAlignment(Qt::AlignHCenter);
    leftLbl5_2->setAlignment(Qt::AlignHCenter);
    leftLbl5_3->setAlignment(Qt::AlignHCenter);
    leftLbl5_4->setAlignment(Qt::AlignHCenter);
    rootUpLeftHLayout5->addWidget(leftLbl5_1);
    rootUpLeftHLayout5->addWidget(leftLbl5_2);
    rootUpLeftHLayout5->addWidget(leftLbl5_3);
    rootUpLeftHLayout5->addWidget(leftLbl5_4);


    rootUpLeftLayout->addLayout(rootUpLeftHLayout1);
    rootUpLeftLayout->addWidget(leftLbl2);
    rootUpLeftLayout->addLayout(rootUpLeftHLayout3);
    rootUpLeftLayout->addLayout(rootUpLeftHLayout4);
    rootUpLeftLayout->addLayout(rootUpLeftHLayout5);

    rootUpLayout->addWidget(rootUpWidgetLeft);


    rootUpWidgetLeft->setMinimumWidth(300);
    for  (int i = 0;i<7;i++){
        rootUpWidgetRight[i] = new DWidget();
        rootUpWidgetRight[i]->setMinimumWidth(100);

        rootUpLayout->addWidget(rootUpWidgetRight[i]);
        rootUpWidgetRight[i]->installEventFilter(this);
        lblLayout[i] = new QVBoxLayout(rootUpWidgetRight[i]);
        lblLayout[i]->setContentsMargins(0,0,0,0);
        lblLayout[i]->setSpacing(0);
        for (int m=0;m<7;m++){
            lbl[i][m] = new DLabel();
            lbl[i][m]->setStyleSheet("color:white");
            lbl[i][m]->setAlignment(Qt::AlignCenter);
            lbl[i][m]->setAttribute(Qt::WA_TranslucentBackground);// 解决qlabel之间的色差问题
            lblLayout[i]->addWidget(lbl[i][m]);
        }
    }
    rootUpWidgetRight[0]->setStyleSheet("background-image: url(:/images/todayBg.png);");

}

void weather::initDownWidget()
{
    //下层主体水平布局
    rootDownWidget = new DWidget();
    rootDownWidget->setMinimumHeight(200);

    rootDownMainLayout = new QHBoxLayout(rootDownWidget);
    rootDownLeftWidget = new DWidget();
//    rootDownLeftWidget->setMaximumWidth(700);

    rootDownLeftLblHLayout = new QHBoxLayout(rootDownLeftWidget);
    rootDownLeftLblHLayout->setContentsMargins(0,0,0,0);
    rootDownLeftLblVLayout = new QVBoxLayout();
    rootDownLeftLblVLayout->setContentsMargins(0,0,0,0);
    rootDownleftLblMain = new DLabel();

    rootDownleftLblMain->setMinimumSize(400,400);


    rootDownWidgetLbl1 = new DWidget();
    rootDownWidgetLbl2 = new DWidget();
    rootDownWidgetLbl3 = new DWidget();
    rootDownWidgetLbl4 = new DWidget();
    rootDownWidgetLbl1->setMaximumWidth(200);
    rootDownWidgetLbl2->setMaximumWidth(200);
    rootDownWidgetLbl3->setMaximumWidth(200);
    rootDownWidgetLbl4->setMaximumWidth(200);
    rootDownleftLblMain->installEventFilter(this);
    rootDownWidgetLbl1->installEventFilter(this);
    rootDownWidgetLbl2->installEventFilter(this);
    rootDownWidgetLbl3->installEventFilter(this);
    rootDownWidgetLbl4->installEventFilter(this);

    rootDownWidgetLbl1->setStyleSheet("background-color:#4989C6;");
    rootDownWidgetLbl2->setStyleSheet("background-color:#E3EBF7;");
    rootDownWidgetLbl3->setStyleSheet("background-color:#E3EBF7;");
    rootDownWidgetLbl4->setStyleSheet("background-color:#E3EBF7;");

    rootDownleftLbl1 = new DLabel();
    rootDownleftLbl2 = new DLabel();
    rootDownleftLbl3 = new DLabel();
    rootDownleftLbl4 = new DLabel();
    rootDownleftLbl11 = new DLabel("全国24小时\n降水量预报");
    rootDownleftLbl21 = new DLabel("FY-4B");
    rootDownleftLbl31 = new DLabel("每日天气提示");
    rootDownleftLbl41 = new DLabel("交通气象预报");
    rootDownleftLbl11->setAlignment(Qt::AlignCenter);
    rootDownleftLbl21->setAlignment(Qt::AlignCenter);
    rootDownleftLbl31->setAlignment(Qt::AlignCenter);
    rootDownleftLbl41->setAlignment(Qt::AlignCenter);

    widgetLblLayout1 = new QHBoxLayout(rootDownWidgetLbl1);
    widgetLblLayout2 = new QHBoxLayout(rootDownWidgetLbl2);
    widgetLblLayout3 = new QHBoxLayout(rootDownWidgetLbl3);
    widgetLblLayout4 = new QHBoxLayout(rootDownWidgetLbl4);

    widgetLblLayout1->addWidget(rootDownleftLbl1);
    widgetLblLayout1->addWidget(rootDownleftLbl11);

    widgetLblLayout2->addWidget(rootDownleftLbl2);
    widgetLblLayout2->addWidget(rootDownleftLbl21);
    widgetLblLayout3->addWidget(rootDownleftLbl3);
    widgetLblLayout3->addWidget(rootDownleftLbl31);
    widgetLblLayout4->addWidget(rootDownleftLbl4);
    widgetLblLayout4->addWidget(rootDownleftLbl41);


    QIcon iconLbl1("/tmp/1.png");
    QIcon iconLbl2("/tmp/2.png");
    QIcon iconLbl3("/tmp/3.png");
    QIcon iconLbl4("/tmp/4.png");
    QPixmap pixmapLbl1 = iconLbl1.pixmap(QSize(100,100));
    QPixmap pixmapLbl2 = iconLbl2.pixmap(QSize(100,100));
    QPixmap pixmapLbl3 = iconLbl3.pixmap(QSize(100,100));
    QPixmap pixmapLbl4 = iconLbl4.pixmap(QSize(100,100));

    rootDownleftLblMain->setStyleSheet("border-image: url(/tmp/1.png)");

    rootDownleftLbl1->setPixmap(pixmapLbl1);
    rootDownleftLbl2->setPixmap(pixmapLbl2);
    rootDownleftLbl3->setPixmap(pixmapLbl3);
    rootDownleftLbl4->setPixmap(pixmapLbl4);


    rootDownLeftLblVLayout->addWidget(rootDownWidgetLbl1);
    rootDownLeftLblVLayout->addWidget(rootDownWidgetLbl2);
    rootDownLeftLblVLayout->addWidget(rootDownWidgetLbl3);
    rootDownLeftLblVLayout->addWidget(rootDownWidgetLbl4);
    rootDownLeftLblHLayout->addWidget(rootDownleftLblMain);
    rootDownLeftLblHLayout->addLayout(rootDownLeftLblVLayout);


    //下层布局，主体是一个水平布局，两个widget
    rootDownRightWidget = new DWidget();
    rootDownRightWidget->setMaximumWidth(500);
    rightDownLayout = new QVBoxLayout(rootDownRightWidget);
    rightDownHLayout = new QHBoxLayout();
    rightDownLbl1 = new DLabel();
    rightDownLbl2 = new DLabel();
    rightDownHLayout->addWidget(rightDownLbl1);
    rightDownHLayout->addWidget(rightDownLbl2);
    rightDownHLayout->addStretch();

    QFont font1;
    font1.setPointSize(15);
    rightDownLbl1->setPixmap(QPixmap(":/images/icon_rmcs.png"));
    rightDownLbl2->setText("实时排行");
    rightDownLbl2->setFont(font1);

    tabWidget = new DTabWidget();
    tabWidget->setStyleSheet(
        "QTabBar::tab {"
        "  font-size: 14px;"                  // 设置字体大小s
        "}"
    );

    downRightbootomlbl = new DLabel("根据今日00时至24时整点实况资料统计");
    downRightbootomlbl->setAlignment(Qt::AlignCenter);




    downRighttable0 = new DTableWidget();
    downRighttable1 = new DTableWidget();
    downRighttable2 = new DTableWidget();
    downRighttable3 = new DTableWidget();
    downRighttable4 = new DTableWidget();
    downRighttable1->setSelectionBehavior(QAbstractItemView::SelectRows);
    downRighttable2->setSelectionBehavior(QAbstractItemView::SelectRows);
    downRighttable3->setSelectionBehavior(QAbstractItemView::SelectRows);
    downRighttable4->setSelectionBehavior(QAbstractItemView::SelectRows);

    connect(downRighttable0,&DTableWidget::doubleClicked,this,[&]{
        int selectedRow = downRighttable0->currentRow();
        QModelIndex index = downRighttable0->model()->index(selectedRow, 1);
        QVariant data = downRighttable0->model()->data(index);
        qDebug()<<data.toString();
        openBrowser->openUrl(data.toString());
    });

    connect(downRighttable1,&DTableWidget::doubleClicked,this,[&]{

        QString city = downRighttable1->selectedItems()[1]->text();
        getWeather(citycode.getCityCode(city));

    });
    connect(downRighttable2,&DTableWidget::doubleClicked,this,[&]{

        QString city = downRighttable2->selectedItems()[1]->text();
        getWeather(citycode.getCityCode(city));

    });
    connect(downRighttable3,&DTableWidget::doubleClicked,this,[&]{

        QString city = downRighttable3->selectedItems()[1]->text();
        getWeather(citycode.getCityCode(city));

    });
    connect(downRighttable4,&DTableWidget::doubleClicked,this,[&]{

        QString city = downRighttable4->selectedItems()[1]->text();
        getWeather(citycode.getCityCode(city));

    });


    initDownRightTable();

    tabWidget->addTab(downRighttable0,"天气资讯");
    tabWidget->addTab(downRighttable1,"今日高温");
    tabWidget->addTab(downRighttable2,"今日低温");
    tabWidget->addTab(downRighttable3,"昼夜温差");
    tabWidget->addTab(downRighttable4,"24小时降水");


    rightDownLayout->addLayout(rightDownHLayout);
    rightDownLayout->addWidget(tabWidget);
    rightDownLayout->addWidget(downRightbootomlbl);

    rootDownMainLayout->addWidget(rootDownLeftWidget);
    rootDownMainLayout->addWidget(rootDownRightWidget);

}

//更新今日高温表格
void weather::updataDownRighttableHighTemperature(QList<QStringList> list)
{
    for (int i=0;i<10;i++){
        if (!list[i].empty()){
            for (int m=0;m<4;m++){
                QTableWidgetItem * nameItem = new QTableWidgetItem(list[i][m]);
                nameItem->setTextAlignment(Qt::AlignCenter);
                downRighttable1->setItem(i,m,nameItem);
            }
        }
    }
}

//更新今日低温
void weather::updataDownRighttableLowTemperature(QList<QStringList> list)
{
    for (int i=0;i<10;i++){
        if (!list[i].empty()){
            for (int m=0;m<4;m++){
                QTableWidgetItem * nameItem = new QTableWidgetItem(list[i][m]);
                nameItem->setTextAlignment(Qt::AlignCenter);
                downRighttable2->setItem(i,m,nameItem);
            }
        }
    }
}

void weather::updataDownRighttableDBTemperature(QList<QStringList> list)
{
    for (int i=0;i<10;i++){
        if (!list[i].empty()){
            for (int m=0;m<4;m++){
                QTableWidgetItem * nameItem = new QTableWidgetItem(list[i][m]);
                nameItem->setTextAlignment(Qt::AlignCenter);
                downRighttable3->setItem(i,m,nameItem);
            }
        }
    }
}

void weather::updataDownRighttableHDTemperature(QList<QStringList> list)
{
    for (int i=0;i<10;i++){
        if (!list[i].empty()){
            for (int m=0;m<4;m++){
                QTableWidgetItem * nameItem = new QTableWidgetItem(list[i][m]);
                nameItem->setTextAlignment(Qt::AlignCenter);
                downRighttable4->setItem(i,m,nameItem);
            }
        }
    }
}

void weather::updateDownRighttableNews(QMap<QString, QString> newsMap)
{
    int index = 0;
    for (auto it = newsMap.begin(); it != newsMap.end(); ++it) {
        QTableWidgetItem * title = new QTableWidgetItem(it.key());
        QTableWidgetItem * url = new QTableWidgetItem(it.value());
        title->setToolTip(it.key());
        downRighttable0->setItem(index,0,title);
        downRighttable0->setItem(index,1,url);
        index+=1;
    }
}

bool weather::eventFilter(QObject *watched,QEvent *event)
{
    if ( watched == rootDownWidgetLbl1){
        if(event->type() == QEvent::Enter){
            rootDownWidgetLbl1->setStyleSheet("background-color:#4989C6");
            rootDownleftLblMain->setStyleSheet("border-image: url(/tmp/1.png)");
            dialogWidget->setStyleSheet("border-image: url(/tmp/1.png)");
        } else if(event->type() == QEvent::Leave) {
            rootDownWidgetLbl1->setStyleSheet("background-color:#E3EBF7;");
        }

    }else if ( watched == rootDownWidgetLbl2){
        if(event->type() == QEvent::Enter){
            rootDownWidgetLbl1->setStyleSheet("background-color:#E3EBF7;");
            rootDownWidgetLbl2->setStyleSheet("background-color:#4989C6");
            rootDownleftLblMain->setStyleSheet("border-image: url(/tmp/2.png)");
            dialogWidget->setStyleSheet("border-image: url(/tmp/2.png)");
        }else if(event->type() == QEvent::Leave) {
            rootDownWidgetLbl2->setStyleSheet("background-color:#E3EBF7;");
        }

    }  else  if ( watched == rootDownWidgetLbl3){
        if(event->type() == QEvent::Enter){
            rootDownWidgetLbl1->setStyleSheet("background-color:#E3EBF7;");
            rootDownWidgetLbl3->setStyleSheet("background-color:#4989C6");
            rootDownleftLblMain->setStyleSheet("border-image: url(/tmp/3.png)");
            dialogWidget->setStyleSheet("border-image: url(/tmp/3.png)");
        }else if(event->type() == QEvent::Leave) {
            rootDownWidgetLbl3->setStyleSheet("background-color:#E3EBF7;");
        }

    } else   if ( watched == rootDownWidgetLbl4){
        if(event->type() == QEvent::Enter){
            rootDownWidgetLbl1->setStyleSheet("background-color:#E3EBF7;");
            rootDownWidgetLbl4->setStyleSheet("background-color:#4989C6");
            rootDownleftLblMain->setStyleSheet("border-image: url(/tmp/4.png)");
            dialogWidget->setStyleSheet("border-image: url(/tmp/4.png)");
        } else if(event->type() == QEvent::Leave) {
            rootDownWidgetLbl4->setStyleSheet("background-color:#E3EBF7;");
        }
    }else  if ( watched == rootDownleftLblMain){
        if(event->type() == QEvent::MouseButtonPress){
            mDialog->exec();
        }
    }
    else{
        for (int i=0;i<7;i++){
            if(watched == rootUpWidgetRight[i]){

                if(event->type() == QEvent::Enter){
                    rootUpWidgetRight[i]->setStyleSheet("background-image: url(:/images/todayBg.png);");
                }
                else if(event->type() == QEvent::Leave) {
                    if (i != 0){
                        rootUpWidgetRight[i]->setStyleSheet("");
                    }
                }else if(event->type() == QEvent::MouseButtonPress){


                }
                break;
            }
        }
    }

    return DWidget::eventFilter(watched,event);//如果没有过滤到，其他的事件都回传给父类
}

